package com.star.ms.common.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.star.ms.common.api.OssApi;
import com.star.ms.common.dao.mapper.user.UserMapper;
import com.star.ms.common.entity.api.OssUploadResult;
import com.star.ms.common.entity.user.User;
import com.star.ms.common.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class OssServiceImpl implements OssService {
    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{"bmp", "jpg",
            "jpeg", "gif", "png"};
    public final static String ERROR = "error";
    public final static String DONE = "done";
    public final static String SUCCESS = "success";
    @Autowired
    private OSS ossClient;
    @Autowired
    private UserMapper userMapper;

    /**
     * 获取默认头像的链接
     * @return 返回格式为[头像名, 头像地址] 的列表
     */
    @Override
    public List<String[]> getDefaultHeadImgLink() {
        List<String[]> imgs = new LinkedList<>();
        // 创建请求
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(OssApi.BUCKET_NAME);
        // 设置前缀
        listObjectsRequest.setPrefix("mall-system/image-default-head");
        // 获取文件
        ObjectListing listing = ossClient.listObjects(listObjectsRequest);
        // 记录文件名和目录

        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
            // 文件的后缀 如 mall-system/xx.png
            String suffix = objectSummary.getKey();
            String[] split = suffix.split("/");
            // 排除根目录 或 不正确的图片
            if(split.length <= 2) continue;
            String [] img = {"", ""};
            img[0]  = split[1];
            img[1] = OssApi.URL_PREFIX + suffix;
            imgs.add(img);
        }
        return imgs;
    }


    @Override
    public OssUploadResult uploadProduct(Long productId, String img64base){
        Pattern pattern = Pattern.compile("image/(.*);");
        Matcher matcher = pattern.matcher(img64base);
        String uploadType = matcher.find() ? matcher.group(1) : null;
        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) { if (type.equals(uploadType)) {isLegal = true; break; }}
        //封装Result对象，并且将文件的byte数组放置到result对象中
        OssUploadResult fileUploadResult = new OssUploadResult();
        if (!isLegal) {
            fileUploadResult.setStatus(ERROR);
            return fileUploadResult;
        }
        //文件新路径
        String filePath = getProductImgPath(productId, uploadType);
        // 上传到阿里云
        try {
            // 上传时需去掉base64编码的data:image/xxx;base64前缀
            ossClient.putObject(OssApi.BUCKET_NAME, filePath, new
                    ByteArrayInputStream(Base64Utils.decodeFromString(img64base.split(",")[1].trim())));
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus(ERROR);
            return fileUploadResult;
        }
        fileUploadResult.setStatus(DONE);
        fileUploadResult.setResponse(SUCCESS);
        String imgUrl = OssApi.URL_PREFIX + filePath;
        fileUploadResult.setImgUrl(imgUrl);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return fileUploadResult;
    }
    @Override
    public OssUploadResult upload(String userCode, String img64base) {
        Pattern pattern = Pattern.compile("image/(.*);");
        Matcher matcher = pattern.matcher(img64base);
        String uploadType = matcher.find() ? matcher.group(1) : null;
        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {

            if (type.equals(uploadType)) {
                isLegal = true;
                break;
            }
        }
        //封装Result对象，并且将文件的byte数组放置到result对象中
        OssUploadResult fileUploadResult = new OssUploadResult();
        if (!isLegal) {
            fileUploadResult.setStatus(ERROR);
            return fileUploadResult;
        }
        //文件新路径
        String filePath = getUserImgPath(userCode, uploadType);
        // 上传到阿里云
        try {
            // 上传时需去掉base64编码的data:image/xxx;base64前缀
            ossClient.putObject(OssApi.BUCKET_NAME, filePath, new
                    ByteArrayInputStream(Base64Utils.decodeFromString(img64base.split(",")[1].trim())));
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus(ERROR);
            return fileUploadResult;
        }
        fileUploadResult.setStatus(DONE);
        fileUploadResult.setResponse(SUCCESS);
        String imgUrl = OssApi.URL_PREFIX + filePath;
        fileUploadResult.setImgUrl(imgUrl);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return fileUploadResult;
    }

    @Override
    public String getUserImgPath(String userCode, String imgType) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return "mall-system/images/users/" + userCode + "/" + sdf.format(System.currentTimeMillis())
                + System.currentTimeMillis() + "." +
                imgType;
    }
    @Override
    public String getProductImgPath(Long productId, String imgType){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return "mall-system/images/products/" + productId + "/" + sdf.format(System.currentTimeMillis())
                + System.currentTimeMillis() + "." +
                imgType;
    }

    @Override
    public OssUploadResult uploadById(Long userId, String img64Base) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId, userId);
        User user = userMapper.selectOne(wrapper);
        assert user != null : "修改头像的用户ID查询结果为空";
        return upload(user.getUsercode(), img64Base);
    }

}
